package com.niuwa.p2p.service.impl.fund;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.niuwa.p2p.core.constant.YeePayCodeEnum;
import com.niuwa.p2p.core.constant.YeePayModeEnum;
import com.niuwa.p2p.core.mvc.entity.PageBean;
import com.niuwa.p2p.core.utils.AppConstants;
import com.niuwa.p2p.core.utils.DateUtil;
import com.niuwa.p2p.core.utils.DictConstant;
import com.niuwa.p2p.core.utils.StringUtil;
import com.niuwa.p2p.core.utils.UUIDUtil;
import com.niuwa.p2p.dao.customer.BaseCustomerDao;
import com.niuwa.p2p.dao.customer.CertAuthDao;
import com.niuwa.p2p.dao.fund.AccountFlowDao;
import com.niuwa.p2p.dao.fund.AcctApplyDao;
import com.niuwa.p2p.dao.fund.ApplyAcctLogDao;
import com.niuwa.p2p.dao.fund.BaseAccountDao;
import com.niuwa.p2p.dao.fund.ChannelAccountDao;
import com.niuwa.p2p.dao.fund.ChlAcctRuleDao;
import com.niuwa.p2p.dao.fund.CustAccountDao;
import com.niuwa.p2p.dao.fund.CustAcctRuleDao;
import com.niuwa.p2p.entity.PageQuery;
import com.niuwa.p2p.entity.customer.BaseCustomer;
import com.niuwa.p2p.entity.customer.CertAuth;
import com.niuwa.p2p.entity.fund.AccountFlow;
import com.niuwa.p2p.entity.fund.AcctApply;
import com.niuwa.p2p.entity.fund.ApplyAcctLog;
import com.niuwa.p2p.entity.fund.BaseAccount;
import com.niuwa.p2p.entity.fund.ChannelAccount;
import com.niuwa.p2p.entity.fund.ChlAcctRule;
import com.niuwa.p2p.entity.fund.CustAccount;
import com.niuwa.p2p.entity.fund.CustAcctRule;
import com.niuwa.p2p.entity.yeepay.cp.RechargeRecords;
import com.niuwa.p2p.entity.yeepay.cp.WithdrawRecords;
import com.niuwa.p2p.entity.yeepay.supple.RechargeRecord;
import com.niuwa.p2p.entity.yeepay.supple.RechargeRecordResponse;
import com.niuwa.p2p.entity.yeepay.supple.SuppleAccountRequest;
import com.niuwa.p2p.entity.yeepay.supple.SuppleAccountResponse;
import com.niuwa.p2p.entity.yeepay.supple.SuppleSingleQueryRequest;
import com.niuwa.p2p.entity.yeepay.supple.SuppleSingleQueryResponse;
import com.niuwa.p2p.entity.yeepay.supple.WithdrawRecord;
import com.niuwa.p2p.entity.yeepay.supple.WithdrawRecordResponse;
import com.niuwa.p2p.service.fund.FundAccountService;
import com.niuwa.p2p.service.yeepay.YeePayService;
import com.niuwa.p2p.utils.IdCardUtil;
@Service
public class FundAccountServiceImpl implements FundAccountService{
	@Autowired
	private BaseAccountDao baseAccountDao;
	@Autowired
	private ChannelAccountDao channelAccountDao;
	@Autowired
	private AcctApplyDao acctApplyDao;
	@Autowired
	private ApplyAcctLogDao applyAcctLogDao;
	@Autowired
	private CustAccountDao custAccountDao;
	@Autowired
	private CustAcctRuleDao custAcctRuleDao;
	@Autowired
	private CustAccountDao custAccoundDao;

	@Autowired
	private ChlAcctRuleDao chlAcctRuleDao;
	
	@Autowired
	private CertAuthDao certAuthDao;
	
	@Autowired
	private BaseCustomerDao baseCustomerDao;
	
	@Autowired
	private AccountFlowDao accountFlowDao;
	
//	@Autowired
	private YeePayService yeePayService;
	
	private static Logger logger = Logger.getLogger(FundAccountServiceImpl.class);

	/**
	 * 查询客户账号列表
	 */
	@Override
	public PageBean<BaseAccount> searchCustomerPage(Map<String, Object> paramMap) {
		assert paramMap.get(PageQuery.PAGEQUERY) != null;
		int totalCount = baseAccountDao.getCustomerCount(paramMap);
		PageBean<BaseAccount> page  = new PageBean<BaseAccount>(totalCount);
		// 当前页
		page.setPage(((PageQuery)paramMap.get(PageQuery.PAGEQUERY)).getPage());
		page.setRows(baseAccountDao.selectCustomerList(paramMap));
		return page;
	}

	/**
	 * 查询渠道账号列表
	 */
	@Override
	public PageBean<BaseAccount> searchChanelPage(Map<String, Object> paramMap) {
		assert paramMap.get(PageQuery.PAGEQUERY) != null;
		int totalCount = baseAccountDao.getChannelCount(paramMap);
		PageBean<BaseAccount> page  = new PageBean<BaseAccount>(totalCount);
		// 当前页
		page.setPage(((PageQuery)paramMap.get(PageQuery.PAGEQUERY)).getPage());
		page.setRows(baseAccountDao.selectChannelList(paramMap));
		return page;
	}
	
	/**
	 * 获取所有渠道账号列表
	 */
	@Override
	public List<ChannelAccount> getAllChannelAccount() {
		return channelAccountDao.selectAllChannelAccount();
	}

	/**
	 * 获取申请账号分页列表
	 */
	@Override
	public PageBean<AcctApply> searchAcctApplyPage(Map<String, Object> paramMap) {
		assert paramMap.get(PageQuery.PAGEQUERY) != null;
		int totalCount = acctApplyDao.getAcctApplyCount(paramMap);
		PageBean<AcctApply> page  = new PageBean<AcctApply>(totalCount);
		// 当前页
		page.setPage(((PageQuery)paramMap.get(PageQuery.PAGEQUERY)).getPage());
		page.setRows(acctApplyDao.selectAcctApplyList(paramMap));
		return page;
	}

	/**
	 * 插入操作日志
	 */
	@Override
	public boolean insertApplyAcctLog(ApplyAcctLog applyAcctLog) {
		return applyAcctLogDao.insert(applyAcctLog) == 0 ? false:true;
	}
	/**
	 * 选择更新账户申请
	 * @param acctApply
	 * @return
	 */
	public boolean updateByPrimaryKeySelective(AcctApply acctApply){
		return acctApplyDao.updateByPrimaryKeySelective(acctApply) > 0 ? true:false;
	}

	/**
	 * 获取最新账号审核结果
	 */
	@Override
	public ApplyAcctLog getNewestAudit(String applyNo) {
		return applyAcctLogDao.getNewestAudit(applyNo);
	}

	/**
	 * 根据账号获取资金客户账号
	 */
	@Override
	public CustAccount getCustAccoutByKey(String accountNo) {
		return custAccountDao.selectByPrimaryKey(accountNo);
	}

	@Override
	public CustAcctRule getCustAcctRule(Long ruleId) {
		return custAcctRuleDao.selectByPrimaryKey(ruleId);
	}

	/**
	 * 根据机构编号获取机构规则
	 */
	@Override
	public CustAcctRule getRuleByOpenOrgNo(String openOrgNo) {
		return custAcctRuleDao.selectByOpenOrgCode(openOrgNo);
	}

	/**
	 * 获取渠道账号规则
	 */
	@Override
	public ChlAcctRule getChlRuleByOpenOrgNo(String openOrgNo) {
		return chlAcctRuleDao.getChlOrgRule(openOrgNo);
	}

	@Override
	public boolean insertBaseAccount(BaseAccount baseAccount) {
		return baseAccountDao.insert(baseAccount) > 0 ? true:false;
	}

	@Override
	public boolean insertChannelAccount(ChannelAccount channelAccount) {
		return channelAccountDao.insert(channelAccount) > 0 ? true:false;
	}

	@Override
	public Long insertChlAcctRule(ChlAcctRule chlAcctRule) {
		return (long) chlAcctRuleDao.insert(chlAcctRule);
	}
	
	public BaseAccount getBaseAccountByAcctNo(String acctNo){
		return baseAccountDao.selectByPrimaryKey(acctNo);
	}
	/**
	 * 检查渠道账号是否存在
	 */
	public boolean isContainsAcctNo(String acctNo){
		BaseAccount baseAccount = baseAccountDao.selectByPrimaryKey(acctNo);
		ChannelAccount channelAccount = channelAccountDao.selectByPrimaryKey(acctNo);
		boolean result = true;
		if(baseAccount == null && channelAccount == null){
			result = false;
		}
		return result;
	}

	
	public boolean saveChannelAccount(BaseAccount baseAccount,ChannelAccount channelAccount,ChlAcctRule chlAcctRule){
		boolean result = true;
		baseAccount.setAcctKind("CHL");//渠道账号
		baseAccount.setCreateTime(new Date());
		result = insertBaseAccount(baseAccount);//插入基本信息
		String isDefault = channelAccount.getIsDefault();
		if("Y".equals(isDefault)){//如果默认
			result = insertChannelAccount(channelAccount);
		}else if("N".equals(isDefault)){//如果自定义
			chlAcctRule.setCreateTime(new Date());
			 insertChlAcctRule(chlAcctRule);
			channelAccount.setChlRuleId(chlAcctRule.getId());
			
			result = insertChannelAccount(channelAccount);
		}
		return result;
		
	}

	@Override
	public ChannelAccount getChannelAccountByAcctNo(String acctNo) {
		return channelAccountDao.selectByPrimaryKey(acctNo);
	}

	@Override
	public ChlAcctRule getChlAcctRuleById(Long id) {
		return chlAcctRuleDao.selectByPrimaryKey(id);
	}

	/**
	 * 更新渠道账号
	 */
	@Override
	public boolean updateChannelAccount(BaseAccount baseAccount,
			ChannelAccount channelAccount, ChlAcctRule chlAcctRule) {
		boolean result = true;
		result = baseAccountDao.updateByPrimaryKey(baseAccount) >0 ?true:false;
		String isDefault = channelAccount.getIsDefault();
		if("Y".equals(isDefault)){//默认
			//channelAccount.setChlRuleId(chlAcctRule.getId());
			result = channelAccountDao.updateByPrimaryKeySelective(channelAccount) > 0?true:false;
		}else if("N".equals(isDefault)){//自定义
			chlAcctRule.setId(null);
			result = chlAcctRuleDao.insert(chlAcctRule) > 0?true:false;
			channelAccount.setChlRuleId(chlAcctRule.getId());
			result = channelAccountDao.updateByPrimaryKeySelective(channelAccount) > 0 ? true : false;
		}
			
		return result;
	}
	@Override
	public boolean updateChannelAccount(BaseAccount baseAccount,
			ChannelAccount channelAccount, ChlAcctRule chlAcctRule,CustAcctRule custAcctRule){
		boolean result = true;
		result = baseAccountDao.updateByPrimaryKey(baseAccount) > 0 ? true:false;
		String controlType = channelAccount.getControlType();
		if("STRONG".equals(controlType)){//强控制
			String isDefault = channelAccount.getIsDefault();
			if("Y".equals(isDefault)){
				result = channelAccountDao.updateByPrimaryKeySelective(channelAccount) > 0?true:false;
			}else if("N".equals(isDefault)){
				chlAcctRule.setId(null);
				result = chlAcctRuleDao.insert(chlAcctRule) > 0?true:false;
				channelAccount.setChlRuleId(chlAcctRule.getId());
				result = channelAccountDao.updateByPrimaryKeySelective(channelAccount) > 0 ? true : false;
			}
		}else if("WEAK".equals(controlType)){//弱控制
			String isDefault = channelAccount.getIsDefault();
			if("Y".equals(isDefault)){
				result = channelAccountDao.updateByPrimaryKeySelective(channelAccount) > 0?true:false;
			}else if("N".equals(isDefault)){
				custAcctRule.setId(null);
				result = custAcctRuleDao.insert(custAcctRule) > 0 ? true : false;
				channelAccount.setChlRuleId(custAcctRule.getId());
				result = channelAccountDao.updateByPrimaryKeySelective(channelAccount) > 0 ? true : false;
			}
		}
		return result;
	}

	/**
	 * 更新用户账号
	 */
	@Override
	public boolean updateCustAccount(BaseAccount baseAccount,
			CustAccount custAccount, CustAcctRule chlAcctRule) {
		boolean result = true;
		result = baseAccountDao.updateByPrimaryKey(baseAccount) > 0 ? true:false;
		String isDefault = custAccount.getIsDefault();
		if("Y".equals(isDefault)){//默认
			result = custAccountDao.updateByPrimaryKey(custAccount) > 0 ? true : false;
		}else if("N".equals(isDefault)){//自定义
			result = custAcctRuleDao.insert(chlAcctRule) > 0 ? true : false;
			custAccount.setCustRuleId(chlAcctRule.getId());
			result = custAccountDao.updateByPrimaryKey(custAccount) > 0 ? true : false;
		}
		return result;
	}
	/**
	 * 账号审核通过
	 * @return
	 */
	public boolean saveAcctApplyPass(String applyNo,Long userId){
		//保存审核操作信息
		ApplyAcctLog applyAcctLog = new ApplyAcctLog();
		applyAcctLog.setApplyNo(applyNo);
		applyAcctLog.setOperateType("PASS");//通过
		applyAcctLog.setOperator(userId);
		applyAcctLog.setCreateTime(new Date());
		boolean result = this.insertApplyAcctLog(applyAcctLog);
		//修改审核申请状态
		/*AcctApply acctApply = new AcctApply();
		acctApply.setApplyNo(applyNo);
		acctApply.setApplyStatus("PASS");
		boolean re = this.updateByPrimaryKeySelective(acctApply);*/
		Map<String,String> map = new HashMap<String,String>();
		map.put("applyStatus", "PASS");
		map.put("applyNo", applyNo);
		boolean re = acctApplyDao.updateStatus(map) > 0 ? true:false;
		if(result && re){
			return true;
		}else{
			return false;
		}
	}
	/**
	 * 账号审核拒绝
	 * @return
	 */
	public boolean saveAcctApplyReject(String applyNo,Long userId,String reason){
		//保存审核操作信息
		ApplyAcctLog applyAcctLog = new ApplyAcctLog();
		applyAcctLog.setApplyNo(applyNo);
		applyAcctLog.setOperateType("REJECT");//拒绝
		applyAcctLog.setOperator(userId);
		applyAcctLog.setCreateTime(new Date());
		applyAcctLog.setRemark(reason);
		boolean result = this.insertApplyAcctLog(applyAcctLog);
		//修改审核申请状态
		/*AcctApply acctApply = new AcctApply();
		acctApply.setApplyNo(applyNo);
		acctApply.setApplyStatus("REJECT");
		boolean re = this.updateByPrimaryKeySelective(acctApply);*/
		Map<String,String> map = new HashMap<String,String>();
		map.put("applyStatus", "REJECT");
		map.put("applyNo", applyNo);
		boolean re = acctApplyDao.updateStatus(map) > 0 ? true:false;
		if(result && re){
			return true;
		}else{
			return false;
		}
	}

	/**
	 * 资金账户【web】
	 * @param custId 客户Id
	 * @return Account 账户实体
	 */
	@Override
	public CustAccount getAccountInfoByCustId(long custId) {
		return custAccoundDao.getAccountInfoByCustId(custId);
	}
	//TODO 交易相关 review - 开户回调
	/**
	* 创建资金账户【web】
	* @param paramMap
	* @return
	*/
	@Override
	public boolean saveFundAccount(Map<String, Object> paramMap) throws Exception {
		boolean result=false;
		String accountNo=(String) paramMap.get("accountNo");//资金账户号
		String realName=(String) paramMap.get("realName");//真实姓名
		String idCardNo=(String) paramMap.get("idCardNo");//证件号
		String custId=(String) paramMap.get("custId");//客户Id
		Date createTime=(Date) paramMap.get("createTime");//客户Id
		//判断用户是否符合开通条件
		CustAccount custAcc=custAccountDao.selectByPrimaryKey(accountNo);
		if (null!=custAcc) {
			//持久化操作【创建资金账号、完成实名认证】
			CustAccount custAccount=new CustAccount();
			custAccount.setAccountNo(accountNo);
			custAccount.setCustId(Long.valueOf(custId));
			custAccount.setAccountStatus(DictConstant.AccountStatus.NORMAL.getCode());
			custAccount.setUsableBalance(new BigDecimal(0));//可用余额
			custAccount.setForzenAmount(new BigDecimal(0));//冻结金额
			custAccount.setAllRechargeAmount(new BigDecimal(0));//累计充值
			custAccount.setWithdrewAmount(new BigDecimal(0));//累计提现
			custAccount.setAllInvestAmount(new BigDecimal(0));//累投金额
			custAccount.setCollectedPrincipal(new BigDecimal(0));
			custAccount.setCollectedRevenue(new BigDecimal(0));
			custAccount.setCollectingPrincipal(new BigDecimal(0));
			custAccount.setCollectingRevenue(new BigDecimal(0));
			int resultO=custAccoundDao.insertSelective(custAccount);
			String authStatus=DictConstant.AuthStatus.AUTH_SUCCESS.getCode();//认证状态[已认证]
			//持久化baseAccount信息
			BaseAccount baseAccount=new BaseAccount();
			baseAccount.setAcctNo(accountNo);
			baseAccount.setAcctName(realName);
			baseAccount.setOpenOrgCode(AppConstants.OPEN_ORG_CODE);
			baseAccount.setOpenOrgName(AppConstants.OPEN_ORG_NAME);
			baseAccount.setCreateTime(createTime);
			baseAccount.setAcctBal(new BigDecimal(0));//可用余额
			int resultT=baseAccountDao.insertSelective(baseAccount);
			//添加身份认证信息
			CertAuth certAuth=new CertAuth();
			certAuth.setCustId(Long.valueOf(custId));
			certAuth.setCustName(realName);
			certAuth.setCertType(DictConstant.certType.SFZ.getCode());//证件类型【身份证】
			certAuth.setCertNo(idCardNo);
			certAuth.setAuthStatus(authStatus);
			certAuth.setAuthCount(1);
			certAuth.setAuthTime(new Date());
			certAuth.setCreateTime(new Date());
			int resultTh=certAuthDao.insert(certAuth);
			//修改用户基本信息
			BaseCustomer baseCust=new BaseCustomer();
			baseCust.setCustName(realName);
			baseCust.setCustId(Long.valueOf(custId));
			baseCust.setCertAuth(authStatus);
			baseCust.setCertNo(idCardNo);
			baseCust.setCertType(DictConstant.certType.SFZ.getCode());
			baseCust.setUpdateTime(new Date());
			/*身份认证成功更新用户基本信息的生日、性别、年龄、星座*/
			baseCust.setBirthday(IdCardUtil.getDate(IdCardUtil.getBirthByIdCard(idCardNo), DateUtil.DATE_FORMAT_YYYY_MM_DD));
			baseCust.setSex(IdCardUtil.getSex(idCardNo));
			baseCust.setConstellation(IdCardUtil.getConstellationById(idCardNo));
			baseCust.setAge(IdCardUtil.getAge(idCardNo));
			
			int resultF=baseCustomerDao.updateBaseCustomer(baseCust);
			if (resultO+resultT+resultTh+resultF==4) {
				logger.info("开通个人资金账户----->账户注册回调操作成功"+new Date());
				result=true;
			}else{
				logger.info("开通个人资金账户----->账户注册回调操作失败"+new Date());
				throw new Exception("账户注册回调操作失败!");
			}
		}else{
			logger.info("开通个人资金账户----->账户不可重复开通"+new Date());
			throw new Exception("账户不可重复开通!");
		}
		return result;
	}

	//TODO 交易相关 review - 充值回调
	/**
	* 资金账户充值【web】
	* @param paramMap
	* @return
	*/
	@Override
	public boolean fundAccountRecharge(Map<String, Object> paramMap) throws Exception {
		boolean result=false;
		String nwPlatNo=(String) paramMap.get("nwPlatNo");//牛娃平台账号
		String accountNo=(String) paramMap.get("accountNo");//用户资金账户号
		String amount=(String) paramMap.get("amount");//金额
		String custId=(String) paramMap.get("custId");//客户Id
		String requestNo=(String) paramMap.get("requestNo");//流水号
		String fee=(String) paramMap.get("fee");//手续费
		//获取用户信息
		BaseCustomer baseCustomer=baseCustomerDao.getBaseCustInfoById(Long.valueOf(custId));
		//判断用户、账户是否对应
		CustAccount account=custAccoundDao.getAccountInfoByCustId(Long.valueOf(custId));
		if (null!=account && accountNo.equals(account.getAccountNo())) {
			//更新可用余额、累计充值金额
			BigDecimal usableBalance = new BigDecimal(amount);  
			usableBalance=usableBalance.add(account.getUsableBalance());
			account.setUsableBalance(usableBalance);
			
			BigDecimal allRechargeAmount = new BigDecimal(amount);  
			allRechargeAmount=allRechargeAmount.add(account.getAllRechargeAmount());
			account.setAllRechargeAmount(allRechargeAmount);
			
			int resultO=custAccoundDao.updateByPrimaryKey(account);
			
			//更新账户余额(可用余额+冻结金额)
			BigDecimal acctBal =account.getUsableBalance();  
			acctBal=acctBal.add(account.getForzenAmount());
			BaseAccount baseAccount=baseAccountDao.selectByPrimaryKey(accountNo);
			baseAccount.setAcctBal(acctBal);
			int resultT=baseAccountDao.updateByPrimaryKey(baseAccount);
			
			//添加充值流水信息
			AccountFlow flow=new AccountFlow();
			flow.setSerialNo(UUIDUtil.getStringUUid());//TODO　暂时使用UUID生成流水号
			flow.setAcctNo(accountNo);
			flow.setAcctName(baseCustomer.getCustName());
			flow.setTransType(DictConstant.transactionType.RECHARGE.getCode());
			flow.setTransAmount(new BigDecimal(amount));
			flow.setTransTime(new Date());
			flow.setDealStatus(DictConstant.flowDealStatus.SUCCESS.getCode().toString());
			flow.setAcctKind(DictConstant.ACCOUNT_KIND.CUST.getCode().toString());
			flow.setTransChl(DictConstant.platForm.P2P.getCode().toString());
			flow.setAcctBal(acctBal);
			flow.setReqNo(requestNo);
			int resultTh=accountFlowDao.insertSelective(flow);
			
			//添加牛娃账户扣除充值手续费流水信息[牛娃平台账户不支持查询，账户余额无法确定]
			flow=new AccountFlow();
			flow.setSerialNo(UUIDUtil.getStringUUid());//TODO　暂时使用UUID生成流水号
			flow.setAcctNo(nwPlatNo);
			flow.setAcctName("牛娃平台账户");//TODO  牛娃平台账户名称
			flow.setTransType(DictConstant.transactionType.TRANS_OUT.getCode());
			flow.setTransAmount(new BigDecimal(fee));
			flow.setOtherAcctNo(accountNo);
			flow.setOtherAcctName(baseCustomer.getCustName());
			flow.setTransTime(new Date());
			flow.setDealStatus(DictConstant.flowDealStatus.SUCCESS.getCode().toString());
			flow.setAcctKind(DictConstant.ACCOUNT_KIND.NW.getCode().toString());
			flow.setTransChl(DictConstant.platForm.P2P.getCode().toString());
			flow.setReqNo(requestNo);
			int resultF=accountFlowDao.insertSelective(flow);
			
			if (resultO+resultT+resultTh+resultF==4) {
				logger.info("资金账户充值----->账户充值回调操作成功"+new Date());
				result=true;
			}else{
				logger.info("资金账户充值----->账户充值回调操作失败"+new Date());
			}
		}else{
			logger.info("资金账户充值----->易宝支付平台账户不存在!"+new Date());
		}		
		return result;
	}
	
	
	//TODO 交易相关 review - 充值完成后对账
	/**
	* 充值完成后对账【web】
	* @param paramMap
	* @return
	*/
	@Override
	public boolean rechargeReconciliation(Map<String, Object> paramMap) throws Exception {
		boolean result=false;
		String accountNo=(String) paramMap.get("accountNo");//资金账户号
		String amount=(String) paramMap.get("amount");//金额
		String custId=(String) paramMap.get("custId");//客户Id
		String requestNo=(String) paramMap.get("requestNo");//流水号
		CustAccount account=custAccoundDao.getAccountInfoByCustId(Long.valueOf(custId));
		//判断用户、账户是否对应
		if (null!=account && accountNo.equals(account.getAccountNo()) ) {
			BaseAccount baseAccount=baseAccountDao.selectByPrimaryKey(account.getAccountNo());
			//查询NWDB获取充值记录[用户充值记录、牛娃账户转出手续费]
			List<AccountFlow> accFlows=accountFlowDao.selectAccountFlowByReqNo(requestNo);
			//单笔业务查询[查询充值记录]
			SuppleSingleQueryRequest request=new SuppleSingleQueryRequest();
			request.setRequestNo(requestNo);
			request.setMode(YeePayModeEnum.RECHARGE_RECORD);//充值记录
			SuppleSingleQueryResponse response=yeePayService.doSingleQuery(request);
			if (null!=accFlows && !accFlows.isEmpty()) {
				if (null!=response) {
					//获取充值Response
					RechargeRecordResponse rechargeRecordResp=response.getRechargeRecordResponse(); 
					YeePayCodeEnum codeEnum=YeePayCodeEnum.valueOf(Integer.parseInt(rechargeRecordResp.getCode()));
					//判断code是否==1
					if (null!=rechargeRecordResp && codeEnum.getValue()==1) {
						//解析Response
						RechargeRecords rechargeRecords=rechargeRecordResp.getRecords();
						if (null!=rechargeRecords) {
							//获取充值记录
							List<RechargeRecord>  records=rechargeRecords.getRecords();
							if (null!=records && !records.isEmpty()) {
								RechargeRecord rechargeRecord=records.get(0);
								//判断状态是否为成功
								if (rechargeRecord.getStatus().equals(DictConstant.yeepayRecordStatus.SUCCESS.getCode())) {
									//获取用户充值记录并比对
									AccountFlow tempAccFlow=null;
									for (AccountFlow accFlow : accFlows) {
										if (accFlow.getAcctKind().equals(DictConstant.ACCOUNT_KIND.CUST.getCode().toString())) {
											tempAccFlow=accFlow;
										}
									}
									if (rechargeRecord.getAmount().equals(tempAccFlow.getTransAmount().toString())
											&& rechargeRecord.getAmount().equals(amount)) {
										//调用易宝接口查询用户信息
										SuppleAccountRequest rechargeRequest=new SuppleAccountRequest();
										rechargeRequest.setPlatformUserNo(accountNo);
										SuppleAccountResponse accResponse=yeePayService.doAccoutInfo(rechargeRequest);
										if (null!=accResponse && YeePayCodeEnum.valueOf(Integer.parseInt(accResponse.getCode())).getValue()==1) {
											//判断账户余额、可用余额、冻结金额
											String balance=accResponse.getBalance();
											String availableAmount=accResponse.getAvailableAmount();
											String freezeAmount=accResponse.getFreezeAmount();
											if (balance.equals(baseAccount.getAcctBal().toString())
													&& availableAmount.endsWith(account.getUsableBalance().toEngineeringString())
													&& freezeAmount.equals(account.getForzenAmount().toString())) {
												result=true;
											}
										}
									}
								}
							}
						}
					}
				}
			}
		}
		return result;
	}
	
	
	//TODO 交易相关 review - 提现回调
	/**
	* 资金账户提现【web】
	* @param paramMap
	* @return
	*/
	@Override
	public boolean fundAccountWithdraw(Map<String, Object> paramMap) throws Exception {
		boolean result=false;
		String accountNo=(String) paramMap.get("accountNo");//资金账户号
		String amount=(String) paramMap.get("amount");//金额
		String custId=(String) paramMap.get("custId");//客户Id
		String requestNo=(String) paramMap.get("requestNo");//流水号
		String fee=(String) paramMap.get("fee");//手续费
		//获取用户信息
		BaseCustomer baseCustomer=baseCustomerDao.getBaseCustInfoById(Long.valueOf(custId));
		//判断用户、账户是否对应
		CustAccount account=custAccoundDao.getAccountInfoByCustId(Long.valueOf(custId));
		if (null!=account && accountNo.equals(account.getAccountNo())) {
			//更新可用余额、累计提现金额
			BigDecimal usableBalance = account.getUsableBalance();  
			//当前可用余额=可用余额-提现金额-提现手续费
			usableBalance=usableBalance.subtract(new BigDecimal(amount)).subtract(new BigDecimal(fee));
			account.setUsableBalance(usableBalance);
			
			BigDecimal withdrewAmount=account.getWithdrewAmount();
			withdrewAmount=withdrewAmount.add(new BigDecimal(amount));
			account.setAllRechargeAmount(withdrewAmount);
			
			int resultO=custAccoundDao.updateByPrimaryKey(account);
			
			//更新账户余额(可用余额+冻结金额)
			BigDecimal acctBal =account.getUsableBalance();  
			acctBal=acctBal.add(account.getForzenAmount());
			BaseAccount baseAccount=baseAccountDao.selectByPrimaryKey(accountNo);
			baseAccount.setAcctBal(acctBal);
			int resultT=baseAccountDao.updateByPrimaryKey(baseAccount);
			
			//添加提现流水信息
			AccountFlow flow=new AccountFlow();
			flow.setSerialNo(StringUtil.GetUniquelyString());
			flow.setAcctNo(accountNo);
			flow.setAcctName(baseCustomer.getCustName());
			flow.setTransType(DictConstant.transactionType.WITHDRAW.getCode());
			flow.setTransAmount(new BigDecimal(amount));
			flow.setTransTime(new Date());
			flow.setDealStatus(DictConstant.flowDealStatus.SUCCESS.getCode().toString());
			flow.setAcctKind(DictConstant.ACCOUNT_KIND.CUST.getCode().toString());
			flow.setTransChl(DictConstant.platForm.P2P.getCode().toString());
			flow.setAcctBal(acctBal);
			flow.setReqNo(requestNo);
			int resultTh=accountFlowDao.insertSelective(flow);
			
			//添加用户扣除提现手续费流水信息
			flow=new AccountFlow();
			flow.setSerialNo(UUIDUtil.getStringUUid());//TODO　暂时使用UUID生成流水号
			flow.setAcctNo(accountNo);
			flow.setAcctName(baseCustomer.getCustName());
			flow.setTransType(DictConstant.transactionType.TRANS_OUT.getCode());
			flow.setTransAmount(new BigDecimal(fee));
			flow.setOtherAcctNo("易宝支付平台自己账号");//TODO 易宝支付平台自己账号
			flow.setOtherAcctName("易宝支付平台自己账户名");//TODO 易宝支付平台自己账户名
			flow.setTransTime(new Date());
			flow.setDealStatus(DictConstant.flowDealStatus.SUCCESS.getCode().toString());
			flow.setAcctKind(DictConstant.ACCOUNT_KIND.CUST.getCode().toString());
			flow.setTransChl(DictConstant.platForm.P2P.getCode().toString());
			flow.setReqNo(requestNo);
			int resultF=accountFlowDao.insertSelective(flow);
			
			if (resultO+resultT+resultTh+resultF==4) {
				logger.error("资金账户充值----->账户充值回调操作成功"+new Date());
				result=true;
			}else{
				logger.error("资金账户充值----->账户充值回调操作失败"+new Date());
			}
		}else{
			logger.error("资金账户充值----->账户不存在!"+new Date());
		}
		return result;
	}

	//TODO 交易相关 review - 提现完成后对账
	/**
	 * 提现完成后对账【web】
	 * @param paramMap
	 * @return
	 */
	@Override
	public boolean withdrawReconciliation(Map<String, Object> paramMap) throws Exception {
		boolean result=false;
		String accountNo=(String) paramMap.get("accountNo");//资金账户号
		String amount=(String) paramMap.get("amount");//金额
		String custId=(String) paramMap.get("custId");//客户Id
		String requestNo=(String) paramMap.get("requestNo");//流水号
		CustAccount account=custAccoundDao.getAccountInfoByCustId(Long.valueOf(custId));
		//判断用户、账户是否对应
		if (null!=account && accountNo.equals(account.getAccountNo()) ) {
			BaseAccount baseAccount=baseAccountDao.selectByPrimaryKey(account.getAccountNo());
			//查询NWDB获取提现记录[提现流水、用户提现扣除手续费流水]
			List<AccountFlow> accFlows=accountFlowDao.selectAccountFlowByReqNo(requestNo);
			//单笔业务查询[查询提现记录]
			SuppleSingleQueryRequest request=new SuppleSingleQueryRequest();
			request.setRequestNo(requestNo);
			request.setMode(YeePayModeEnum.RECHARGE_RECORD);//充值记录
			SuppleSingleQueryResponse response=yeePayService.doSingleQuery(request);
			if (null!=accFlows && !accFlows.isEmpty()) {
				if (null!=response) {
					//获取提现Response
					WithdrawRecordResponse withdrawRecordResponse=response.getWithdrawRecordResponse();
					YeePayCodeEnum codeEnum=YeePayCodeEnum.valueOf(Integer.parseInt(withdrawRecordResponse.getCode()));
					//判断code是否==1
					if (null!=withdrawRecordResponse && codeEnum.getValue()==1) {
						//解析Response
						WithdrawRecords withdrawRecords=withdrawRecordResponse.getRecords();
						if (null!=withdrawRecords) {
							//获取充值记录
							List<WithdrawRecord>  records=withdrawRecords.getRecords();
							if (null!=records && !records.isEmpty()) {
								WithdrawRecord  withdrawRecord=records.get(0);
								//判断状态是否为成功
								if (withdrawRecord.getStatus().equals(DictConstant.yeepayRecordStatus.SUCCESS.getCode())) {
									//获取用户充值记录并比对
									AccountFlow tempAccFlow=null;
									for (AccountFlow accFlow : accFlows) {
										if (accFlow.getAcctKind().equals(DictConstant.ACCOUNT_KIND.CUST.getCode().toString())) {
											tempAccFlow=accFlow;
										}
									}
									if (withdrawRecord.getAmount().equals(tempAccFlow.getTransAmount().toString())
											&& withdrawRecord.getAmount().equals(amount)) {
										//调用易宝接口查询用户信息
										SuppleAccountRequest rechargeRequest=new SuppleAccountRequest();
										rechargeRequest.setPlatformUserNo(accountNo);
										SuppleAccountResponse accResponse=yeePayService.doAccoutInfo(rechargeRequest);
										if (null!=accResponse && YeePayCodeEnum.valueOf(accResponse.getCode()).getValue()==1) {
											//判断账户余额、可用余额、冻结金额
											String balance=accResponse.getBalance();
											String availableAmount=accResponse.getAvailableAmount();
											String freezeAmount=accResponse.getFreezeAmount();
											if (balance.equals(baseAccount.getAcctBal().toString())) {
												if (availableAmount.endsWith(account.getUsableBalance().toEngineeringString())) {
													if (freezeAmount.equals(account.getForzenAmount().toString())) {
														result=true;
													}
												}
											}
										}
									}
								}
							}
						}
					}
				}
			}
		}
		return result;
	}

	@Override
	public boolean disableFundAccount(Map<String, Object> paramMap) throws Exception {
		boolean result=false;
		String accountNo=(String) paramMap.get("accountNo");//资金账户号
		CustAccount custAccount=new CustAccount();
		custAccount.setAccountNo(accountNo);
		custAccount.setAccountStatus(DictConstant.AccountStatus.DISABLED.getCode());//禁用
		int resultCount=custAccoundDao.updateByPrimaryKey(custAccount);
		if (resultCount==1) {
			result=true;
		}
		return result;
	}
}
